/** 
 * Stolen from:
 *  http://www.arduino.cc/en/Tutorial/ShiftIn
 *
 */


// important pins on CD4021 shift register chip
// dataPin  - 3
// latchPin - 9
// clockPin - 10

//define where your pins are
//int clockPin = 7;
//int latchPin = 8;
//int dataPin  = 9;

// what the ArtHeist board has
int dataPin  = 7;
int latchPin = 6;
int clockPin = 5;
const int registerCount = 4;

//variables to hold the data 
byte registerData[4];

void setup() {
  Serial.begin(19200);

  //define pin modes
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT); 
  pinMode(dataPin,  INPUT);

}

void loop() {

  //Pulse the latch pin:
  digitalWrite(latchPin,1);   // set it to 1 to collect parallel data
  delayMicroseconds(20);
  digitalWrite(latchPin,0);   // set it to 0 to transmit data serially  

  // collect each shift register into a byte
  // the register attached to Arduino directly comes in first 
  for( int i = 0; i< registerCount; i++ ) {
    registerData[i] = shiftIn(dataPin, clockPin);
  }

  // Print out the results.
  // leading 0's at the top of the byte (7, 6, 5, etc) will be 
  // dropped before the first pin that has a high input reading  
  for( int i=0; i< registerCount; i++ ) {
    Serial.println(registerData[i], BIN);
  }
  Serial.println("-------------------");

  delay(500);

}


////// ----------------------------------------shiftIn function
///// just needs the location of the data pin and the clock pin
///// it returns a byte with each bit in the byte corresponding
///// to a pin on the shift register. leftBit 7 = Pin 7 / Bit 0= Pin 0
byte shiftIn(int myDataPin, int myClockPin)
{
  int i;
  int temp = 0;
  byte myDataIn = 0;
  
  pinMode(myClockPin, OUTPUT);
  pinMode(myDataPin, INPUT);

  //we will be holding the clock pin high 8 times (0,..,7) at the
  //end of each time through the for loop
  
  //at the begining of each loop when we set the clock low, it will
  //be doing the necessary low to high drop to cause the shift
  //register's DataPin to change state based on the value
  //of the next bit in its serial information flow.
  //The register transmits the information about the pins from pin 7 to pin 0
  //so that is why our function counts down
  for (i=7; i>=0; i--)
  {
    digitalWrite(myClockPin, 0);
    delayMicroseconds(2);
    temp = digitalRead(myDataPin);
    if (temp) {
      myDataIn = myDataIn | (1 << i);        //set the bit to 0 no matter what
    }
    digitalWrite(myClockPin, 1);
  }

  return myDataIn;
}
